<template>
	<view class="jobs-page">
		<view class="header-bg">
		<!-- 顶部头部 -->
		<view class="header">
			<!-- 状态栏占位 -->
			<view class="status-bar"></view>
			<!-- 头部内容 -->
			<view class="header-content">
				<view class="header-left">
					<view class="logo">
						<image class="logo-img" src="@/static/logo.png"></image>
						<text class="logo-text">鸿匠</text>
						<text class="logo-sub">HR</text>
					</view>
				</view>
				<view class="header-center">
					<!-- <text class="slogan">信息真 | 发薪准</text> -->
				</view>
				<view class="header-right">
					
				</view>
			</view>
		</view>
		<!-- 搜索和筛选区域 -->
		<view class="search-section">
			<!-- Tab切换 -->
			<view class="tab-container">
				<view class="tab-tabs">
					<view 
						v-if="showTodayTab"
						class="tab-item"
						:class="{ active: activeTab === 'today' }"
						@click="switchTab('today')"
					>
						<text class="tab-text">今日在招</text>
						<view v-if="activeTab === 'today'" class="tab-underline"></view>
					</view>
					<view 
						class="tab-item"
						:class="{ active: activeTab === 'pre' }"
						@click="switchTab('pre')"
					>
						<text class="tab-text">预招岗位</text>
						<view v-if="activeTab === 'pre'" class="tab-underline"></view>
					</view>
				</view>
                <view class="search-icon" @click="goToSearch">
                    <u-icon name="search" size="24" color="#333333"></u-icon>
                </view>
			</view>
			<!-- 城市导航 -->
			<scroll-view class="city-tabs" scroll-x="true">
				<view 
					v-for="(city, index) in cities" 
					:key="index"
					class="city-tab"
					:class="{ active: activeCity === city.name }"
					@click="selectCity(city)"
				>
					{{ city.name }}
				</view>
			</scroll-view>
			
			<!-- 筛选选项 -->
			<view class="filter-box">
				<view class="filter-tabs">
					<view 
						v-for="(filter, index) in filters" 
						:key="index"
						class="filter-tab"
						:class="{ active: activeFilter === filter.name }"
						@click="selectFilter(filter.name)"
					>
						{{ filter.name }}
					</view>
				</view>
                <view class="filter-right">
                    <view class="filter-select" v-if="activeTab === 'pre'" @click="showDatePicker">
						<text class="filter-text">{{ selectedDate || '日期' }}</text>
						<u-icon name="arrow-down-fill" size="12" color="#999999"></u-icon>
					</view>
					<view class="filter-select" @click="openRegionPicker">
						<text class="filter-text">{{ selectedRegionText }}</text>
						<u-icon name="arrow-down-fill" size="12" color="#999999"></u-icon>
					</view>
					<view class="filter-select" @click="openTagSelector">
						<text class="filter-text">{{ selectedTagsText }}</text>
						<u-icon name="arrow-down-fill" size="12" color="#999999"></u-icon>
					</view>
				</view>
			</view>
		</view>
</view>
		
		<!-- 工作列表 -->
        <u-list 
            class="job-list"
            :class="{ 'is-empty': !loading && jobList.length === 0 }"
			height="calc(100vh - 240rpx - var(--status-bar-height) - env(safe-area-inset-top) - env(safe-area-inset-bottom))"
			:loading="loading"
			:finished="finished"
			@load="loadMore"
			@scrolltolower="loadMore"
			:immediate-check="false"
			:enable-back-to-top="false"
			:lower-threshold="50"
		>
		<!-- 实名认证卡片 -->
		<u-list-item>
		<view v-if="!userStore.isVerified.value" class="verification-card" @click="goToVerification">
			<view class="verification-content">
				<view class="verification-left">
					<view class="avatar-icon">
						<img class="avatar-icon-img" src="@/static/icon/avatar.png"></img>
					</view>
					<view class="verification-text">
						<text class="main-text">您还未实名认证</text>
						<text class="sub-text">实名后可一键报名快速入职,解锁更...</text>
					</view>
				</view>
				<view class="verification-right">
					<u-button 
						type="primary" 
						size="mini" 
						:custom-style="verificationBtnStyle"
					>
						去实名
					</u-button>
				</view>
			</view>
		</view>
		</u-list-item>
		<!-- 加载状态指示器 -->
		<u-list-item>
		<view v-if="loading && jobList.length === 0" class="loading-indicator">
			<u-loading-icon mode="spinner" size="40" color="var(--u-primary)"></u-loading-icon>
			<text class="loading-text">正在加载岗位信息...</text>
		</view>
		</u-list-item>
		<!-- 空数据占位符 -->
		<u-list-item>
        <view v-if="!loading && jobList.length === 0" class="empty-state">
			<view class="empty-illustration">
				<img src="@/static/icon/empty.png" />
			</view>
			<text class="empty-text">暂无招聘信息</text>
			<view class="empty-actions">
				<view class="action-btn refresh-btn" @click="refreshData">
					<text class="btn-text">刷新重试</text>
				</view>
			</view>
		</view>
		</u-list-item>
		<!-- 工作列表项 -->
		<u-list-item 
			v-for="(job, index) in jobList" 
			:key="index"
		>
				<view class="job-card" @click="viewJob(job)">
					<view class="job-header">
						<view class="job-date">
							<view class="job-title">
								<view class="job-title-box" v-if="job.date !== '今日'">
									<u-icon name="calendar" size="24" color="var(--u-primary)"></u-icon>
									<text class="date-text">{{ job.date }}</text>
								</view>
								<text class="job-title-text">{{ job.title }}</text>
							</view>
						</view>
						
						<view class="job-salary">{{ job.salary }}</view>
					</view>
					
					
					
					<view class="job-location">{{ job.location }}{{ job.distance ? ' ' + job.distance + 'km' : '' }}</view>
					
					<view class="job-tags">
						<view 
							v-for="(tag, tagIndex) in job.tags" 
							:key="tagIndex"
							class="job-tag"
						>
							<text v-if="tag.icon" class="tag-icon">{{ tag.icon }}</text>
							<text class="tag-text">{{ tag.name }}</text>
						</view>
					</view>
					
					<!-- 还招岗位展示 -->
					<view v-if="job.positionName" class="job-positions">
						<text class="positions-label">还招：</text>
						<text class="positions-text">{{ job.positionName }}</text>
					</view>
                    
                    <view class="job-engagement">
						<view class="engagement-left">
							<view class="user-avatars">
								<u-avatar-group :urls="job.avatars" size="18" gap="0.4"></u-avatar-group>
							</view>
							<text class="engagement-text">{{ job.engagement }}</text>
						</view>
						<view 
							class="apply-btn" 
							
							
						>
						<!-- :class="{ 'disabled': job.signup }" -->
						<!-- @click.stop="job.signup ? null : applyJob(job, index)" -->
							<!-- <text class="apply-text">{{ job.signup ? '已报名' : '一键报名' }}</text> -->
							<text class="apply-text">一键报名</text>
						</view>
					</view>
				</view>
			</u-list-item>
			
			<!-- Loading状态 -->
			<u-list-item v-if="loading && jobList.length > 0">
				<view class="loading-item">
					<u-loading-icon mode="spinner" size="30" color="var(--u-primary)"></u-loading-icon>
					<text class="loading-text">加载中...</text>
				</view>
			</u-list-item>
			<u-list-item>
				<view  style="height: 100rpx;"></view>
			</u-list-item>
		</u-list>
		
		<!-- 日历弹窗 -->
		<CalendarJobPicker
			v-model:show="showCalendar"
			v-model="selectedDate"
			:jobDataByDate="jobDataByDate"
			@select="onDateSelect"
		/>
		
		<!-- 地域选择弹窗 -->
		<RegionPicker
			v-model:show="showRegionPicker"
			v-model="selectedRegion"
			:type="2"
			@confirm="onRegionConfirm"
		/>
		
		<!-- 标签选择弹窗 -->
		<TagSelector
			v-model:show="showTagSelector"
			v-model="selectedTagCodes"
			@confirm="onTagConfirm"
		/>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import { jobApi, userApi } from '@/api/api-helper.js'
import CalendarJobPicker from '@/components/CalendarJobPicker.vue'
import RegionPicker from '@/components/RegionPicker.vue'
import TagSelector from '@/components/TagSelector.vue'
import { userStore } from '@/stores/userStore'

// 城市数据
const cities = ref([
	{ name: '推荐', hotArea: '' }
])

// 筛选选项
const filters = ref([
	{ name: '热度' },
	{ name: '工价' },
	{ name: '附近' },
])

// API 相关状态
const loading = ref(false) // 初始设置为true，表示页面正在加载
const finished = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

// 查询参数 - 参考接口文档2.0的 HirePagination
const queryParams = ref({
	keyword: '',
	pageSize: 10,
	sort: 'desc',
	sidx: '',
	currentPage: 1,
	type: 'progress', // progress:今日在招 ready:预招岗位
	order: 'signUpPersons', // signUpPersons:热度 workPrice:工价 location:附近
	homeArea: '', // 首页地区查询
	area: '',
	province: '',
	ids: [],
	customize: [],
	eosKeyword: '',
	longitude: '114.0239180',
	latitude: '22.7338490',
	openId: '', // 微信openId
	label: [] // 标签
})

// 工作列表数据
const jobList = ref([])

// 当前选中的城市和筛选
const activeCity = ref('推荐')
const activeFilter = ref('热度')

// Tab切换相关
const activeTab = ref('today') // 默认选中"今日在招"
const showTodayTab = ref(true) // 控制是否显示"今日在招"选项

// 下拉加载相关
const page = ref(1)

// 日历相关
const showCalendar = ref(false)
const selectedDate = ref('')

// 岗位数据 - 模拟从API获取的数据
const jobDataByDate = ref({
	'2025-07-30': { count: 98, available: true },
	'2025-07-31': { count: 2, available: true },
	'2025-08-01': { count: 2, available: true },
	'2025-08-02': { count: 1, available: true },
	'2025-08-03': { count: 1, available: true },
	// 其他日期都没有岗位数据，显示"暂无"
})



// 选择城市
const selectCity = (city: any) => {
	activeCity.value = city.name
	
	// 重置地域选择器
	selectedRegion.value = ''
	selectedRegionText.value = '地域'
	
	// 根据城市更新查询参数
	if (city.name === '推荐') {
		queryParams.value.homeArea = ''
		queryParams.value.area = ''
		queryParams.value.province = ''
		queryParams.value.ids = []
	} else {
		// 使用热门城市返回的hotArea字段
		queryParams.value.homeArea = city.hotArea
		queryParams.value.area = ''
		queryParams.value.province = ''
		queryParams.value.ids = []
	}
	
	// 重新获取数据
	currentPage.value = 1
	finished.value = false
	fetchJobList()
}

// 选择筛选条件
const selectFilter = async (filterName: string) => {
	activeFilter.value = filterName
	
	// 根据筛选条件更新排序参数
	if (filterName === '热度') {
		queryParams.value.order = 'signUpPersons'
	} else if (filterName === '工价') {
		queryParams.value.order = 'workPrice'
	} else if (filterName === '附近') {
		queryParams.value.order = 'location'
		// 获取用户地理位置坐标
		await getUserLocation()
	}
	
	// 重新获取数据
	currentPage.value = 1
	finished.value = false
	fetchJobList()
}

// 获取热门城市列表
const getHotCities = async () => {
	try {
		const result = await jobApi.getHotArea()
		if (result && result.code === 200 && result.data) {
			// 添加"推荐"选项到开头
			const hotCities = [
				{ name: '推荐', hotArea: '' },
				...result.data.map((city: any) => ({
					name: city.name,
					hotArea: city.hotArea
				}))
			]
			cities.value = hotCities
			console.log('获取热门城市成功:', hotCities)
		}
	} catch (error) {
		console.error('获取热门城市失败:', error)
		// 如果接口失败，使用默认城市列表
		cities.value = [
			{ name: '推荐', hotArea: '' },
			{ name: '深圳', hotArea: '["440000000000","440300000000"]' },
			{ name: '惠州', hotArea: '["440000000000","441300000000"]' },
			{ name: '东莞', hotArea: '["440000000000","441900000000"]' }
		]
	}
}

// 获取用户地理位置坐标
const getUserLocation = () => {
	return new Promise((resolve, reject) => {
		// 检查是否支持地理位置
		if (!uni.getLocation) {
			console.log('当前环境不支持地理位置')
			resolve()
			return
		}
		
		// 获取用户地理位置
		uni.getLocation({
			type: 'wgs84', // 使用国测局坐标系
			success: (res) => {
				console.log('获取地理位置成功:', res)
				// 更新查询参数中的经纬度
				queryParams.value.longitude = res.longitude.toString()
				queryParams.value.latitude = res.latitude.toString()
				console.log('更新后的查询参数:', queryParams.value)
				resolve()
			},
			fail: (err) => {
				console.error('获取地理位置失败:', err)
				// 如果获取失败，显示提示
				uni.showToast({
					title: '获取位置失败，请检查位置权限',
					icon: 'none'
				})
				resolve() // 即使失败也继续执行，使用默认坐标
			}
		})
	})
}

// Tab切换
const switchTab = (tabName: string) => {
	// 如果尝试切换到今日在招但该选项已被隐藏，则阻止切换
	if (tabName === 'today' && !showTodayTab.value) {
		console.log('今日在招选项已被隐藏，无法切换')
		return
	}
	
	activeTab.value = tabName
	
	// 根据Tab更新查询参数
	if (tabName === 'today') {
		queryParams.value.type = 'progress' // 今日在招
	} else if (tabName === 'pre') {
		queryParams.value.type = 'ready' // 预招岗位
	}
	
	// 重置分页并重新获取数据
	currentPage.value = 1
	finished.value = false
	fetchJobList()
}


// 跳转到实名认证页面
const goToVerification = () => {
	uni.navigateTo({
		url: '/pages/verification/verification'
	})
}

// 实名认证按钮样式
const verificationBtnStyle = {
	backgroundColor: '#007AFF',
	borderColor: '#007AFF',
	color: '#FFFFFF',
	fontSize: '24rpx',
	padding: '12rpx 24rpx',
	borderRadius: '20rpx'
}
// 获取招聘信息列表
const fetchJobList = async (isLoadMore = false) => {
	if (loading.value) return
	
	try {
		console.log('设置loading为true')
		loading.value = true
		
		// 更新查询参数
		queryParams.value.currentPage = isLoadMore ? currentPage.value + 1 : 1
		
		// 添加openId到查询参数
		const openId = userStore.getOpenId()
		if (openId) {
			queryParams.value.openId = openId
		}
		
		console.log('查询参数:', queryParams.value)
		const result = await jobApi.getListToApp(queryParams.value)
		
		if (result && result.code === 200) {
			const responseData = result.data || {}
			const newJobs = responseData.list || []
			const pagination = responseData.pagination || {}
			
			// 转换API数据为前端格式 - 根据接口文档2.0的HireHomeVO
			console.log('原始岗位数据:', newJobs)
			
			const formattedJobs = newJobs.map((job: any) => {
				
				return {
					id: job.hireRecruitUseId, // 岗位id - 使用hireRecruitUseEntryId
					hireRecruitUseId: job.hireRecruitUseId, // 岗位id - 使用hireRecruitUseEntryId
					hireRecruitUseEntryId: job.hireRecruitUseEntryId, // 岗位id - 使用hireRecruitUseEntryId
					date: formatDate(job.hireStartDate), // 岗位日期
					title: job.hireName || '招聘岗位', // 招聘计划标题
					useWorkType: job.useWorkType || '正式工', // 用工模式
					salary: job.workPrice ? `${job.workPrice}` : '面议', // 工价
					location: formatLocation(job.customerName, job.address), // 企业名称
					address: job.address, //地址
					detailAddress: job.detailAddress, //地址
					customerName: job.customerName, // 企业名称
					distance: job.distance, // 距离字段
					signup: job.signup, // 是否已报名
					positionName: job.positionName, // 职位
					tags: parseTags(job.enterpriseLabel), // 标签列表
					avatars: job.pictureList || [],
					engagement: formatEngagement(job.followerCount),
					// 保留原始数据用于详情页
					rawData: job
				}
			})
			
			if (isLoadMore) {
				jobList.value.push(...formattedJobs)
				currentPage.value++
			} else {
				jobList.value = formattedJobs
				currentPage.value = 1
			}
			
			// 根据分页信息判断是否还有更多数据
			const currentPageNum = pagination.currentPage || 1
			const pageSizeNum = pagination.pageSize || 10
			const totalNum = pagination.total || 0
			
			if (currentPageNum * pageSizeNum >= totalNum) {
				finished.value = true
			}
		} else {
			uni.showToast({
				title: result?.msg || '获取数据失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('获取招聘信息失败:', error)
		uni.showToast({
			title: '网络错误，请重试',
			icon: 'none'
		})
	} finally {
		console.log('设置loading为false')
		loading.value = false
	}
}

// 数据转换函数
const formatDate = (dateStr: string) => {
	if (!dateStr) return '今日'
	try {
		const date = new Date(dateStr)
		const month = (date.getMonth() + 1).toString().padStart(2, '0')
		const day = date.getDate().toString().padStart(2, '0')
		return `${month}月${day}日`
	} catch (error) {
		console.error('日期格式化失败:', error, dateStr)
		return '今日'
	}
}

const formatLocation = (customerName: string, address: any) => {
    if (!customerName && !address) return '未知地点'
    let location = customerName || ''
    if (address) {
        if (typeof address === 'string') {
            // 直接字符串，如 “广东省-深圳市” 或其它地點描述
            location = location ? `${location} ${address}` : address
        } else if (address.province || address.city) {
            // 對象形式
            if (address.province && address.city) {
                location += `${location ? ' ' : ''}${address.province}-${address.city}`
            } else if (address.province) {
                location += `${location ? ' ' : ''}${address.province}`
            } else if (address.city) {
                location += `${location ? ' ' : ''}${address.city}`
            }
        }
    }
    return location
}

const parseTags = (enterpriseLabel: string) => {
	if (!enterpriseLabel) return []
	
	try {
		// 假设标签是JSON字符串或逗号分隔的字符串
		let tags = []
		if (enterpriseLabel.startsWith('[')) {
			tags = JSON.parse(enterpriseLabel)
		} else {
			tags = enterpriseLabel.split(',').map(tag => tag.trim())
		}
		
		return tags.map(tag => ({
			name: tag,
			icon: getTagIcon(tag)
		}))
	} catch (error) {
		return []
	}
}

const getTagIcon = (tag: string) => {
	const iconMap: { [key: string]: string } = {
		'报销车费': '💰',
		'可借支': '💳',
		'包住': '🏠',
		'报销体检费': '🏥',
		'空调宿舍': '❄️',
		'五险一金': '🛡️',
		'双休': '📅',
		'年终奖': '🎁'
	}
	return iconMap[tag] || '🏷️'
}

const formatEngagement = (followerCount: number) => {
	if (!followerCount) return '暂无关注'
	if (followerCount >= 100) {
		return `已关注 ${Math.floor(followerCount / 100) * 100}+`
	}
	return `已关注 ${followerCount}+`
}

// 加载更多
const loadMore = () => {
	console.log('loadMore 被触发')
	console.log('finished:', finished.value)
	console.log('loading:', loading.value)
	
	if (!finished.value && !loading.value) {
		console.log('开始加载更多数据')
		fetchJobList(true)
	} else {
		console.log('不满足加载条件') 
	}
}

// 刷新数据
const refreshData = async () => {
	try {
		// loading.value = true
		currentPage.value = 1
		finished.value = false
		await fetchJobList()
		uni.showToast({
			title: '刷新成功',
			icon: 'success',
			duration: 1500
		})
	} catch (error) {
		console.error('刷新数据失败:', error)
		uni.showToast({
			title: '刷新失败，请重试',
			icon: 'none'
		})
	}
}

// 查看工作详情
const viewJob = (job: any) => {
	console.log('点击岗位卡片:', job)
	console.log('岗位ID (hireRecruitUseEntryId):', job.hireRecruitUseId)
	console.log('原始数据中的hireRecruitUseEntryId:', job.rawData?.hireRecruitUseEntryId)
	
	const url = `/pages/job-details/job-details?jobId=${job.hireRecruitUseId}`
	console.log('跳转URL:', url)
	
	uni.navigateTo({
		url: url,
		success: () => {
			console.log('跳转成功')
		},
		fail: (error) => {
			console.error('跳转失败:', error)
		}
	})
}

// 一键报名
const applyJob = (job: any, index: number) => {
	// 检查用户是否已实名认证
	if (!userStore.isVerified.value) {
		uni.showModal({
			title: '提示',
			content: '您还未实名认证，请先完成实名认证后再报名',
			confirmText: '去认证',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) {
					// 跳转到实名认证页面
					uni.navigateTo({
						url: '/pages/verification/verification'
					})
				}
			}
		})
		return
	}
	
	// 传递完整的岗位信息到报名页面
	const params = {
		jobId: job.hireRecruitUseId,
		hireRecruitUseId: job.hireRecruitUseId, // 岗位id - 使用hireRecruitUseEntryId
		hireRecruitUseEntryId: job.hireRecruitUseEntryId, 
		jobTitle: job.title,
		jobSalary: job.salary,
		jobLocation: job.location,
		customerName: job.customerName,
		useWorkType: job.useWorkType,
		address: job.address,
		detailAddress: job.detailAddress,
		positionName: job.positionName,
		jobData: encodeURIComponent(JSON.stringify(job.rawData || job))
	}
	
	uni.navigateTo({
		url: `/pages/job-application/job-application?${Object.entries(params).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&')}`
	})
}

// 显示日期选择器
const showDatePicker = () => {
	showCalendar.value = true
}

// 地域选择相关
const showRegionPicker = ref(false)
const selectedRegion = ref('')
const selectedRegionText = ref('地域')

// 标签选择相关
const showTagSelector = ref(false)
const selectedTags = ref<string[]>([]) // 存儲選中標籤的ID數組
const selectedTagCodes = ref<string[]>([]) // 存儲選中標籤的enCode數組
const selectedTagsText = ref('自定义')

const openRegionPicker = () => {
	showRegionPicker.value = true
}

// 地域選擇回調：接收 { provinceId, cityId, cityName }
const onRegionConfirm = (payload: any) => {
    if (!payload || !payload.cityId) {
        // 全部
        selectedRegion.value = ''
        selectedRegionText.value = '地域'
        queryParams.value.area = ''
        queryParams.value.province = ''
        queryParams.value.ids = []
        // 重置热门城市到推荐
        activeCity.value = '推荐'
        queryParams.value.homeArea = ''
        fetchJobList()
        return
    }
    const { provinceId, cityId, cityName } = payload
    selectedRegion.value = cityId
    selectedRegionText.value = cityName || '地域'
    // 保存省/市ID，並組裝父子結構字符串陣列
    queryParams.value.province = ''
    queryParams.value.area = `["${provinceId}","${cityId}"]`
    queryParams.value.ids = []
    // 重置热门城市到推荐
    activeCity.value = '推荐'
    queryParams.value.homeArea = ''
    fetchJobList()
}

const onDateSelect = (dateStr: string, dateObj: Date) => {
	console.log('选择日期:', dateStr, dateObj)
	// 这里可以根据选择的日期更新查询参数
	// 例如：添加日期筛选条件到queryParams
	// 然后重新获取岗位列表
	currentPage.value = 1
	finished.value = false
	fetchJobList()
}

const openTagSelector = () => {
	showTagSelector.value = true
}

const onTagConfirm = (tags: string[]) => {
	selectedTagCodes.value = tags // 存儲選中的標籤enCode數組
	if (tags.length === 0) {
		selectedTagsText.value = '自定义'
		// 清空標籤查詢參數
		queryParams.value.label = []
	} else {
		selectedTagsText.value = `${tags.length}项`
		// 將選中的標籤enCode數組設置到查詢參數的label字段中
		queryParams.value.label = tags
	}
	
	// 重新獲取崗位列表
	currentPage.value = 1
	finished.value = false
	fetchJobList()
}

const getCityName = (cityId: string) => {
	const cityMap: { [key: string]: string } = {
		'shenzhen': '深圳',
		'dongguan': '东莞',
		'huizhou': '惠州',
		'guangzhou': '广州',
		'zhongshan': '中山',
		'jiangmen': '江门',
		'zhuhai': '珠海',
		'foshan': '佛山',
		'suzhou': '苏州(含昆山)',
		'shanghai': '上海',
		'nanjing': '南京',
		'wuxi': '无锡',
		'jiaxing': '嘉兴',
		'other': '其他'
	}
	return cityMap[cityId] || '未知'
}

// 跳轉到搜索頁
const goToSearch = () => {
  uni.navigateTo({ url: '/pages/search/search' })
}

// 检查当前时间并更新Tab显示状态
const checkTimeAndUpdateTabs = () => {
	const now = new Date()
	const currentHour = now.getHours()
	const currentMinute = now.getMinutes()
	
	// 如果当前时间超过下午3点（15:00），则隐藏今日在招选项
	if (currentHour > 15 || (currentHour === 15 && currentMinute >= 0)) {
		console.log('当前时间已超过下午3点，隐藏今日在招选项')
		showTodayTab.value = false
		
		// 如果当前选中的是今日在招，则自动切换到预招岗位
		if (activeTab.value === 'today') {
			activeTab.value = 'pre'
			queryParams.value.type = 'ready' // 预招岗位
		}
	} else {
		console.log('当前时间未超过下午3点，显示今日在招选项')
		showTodayTab.value = true
		
		// 确保查询参数与当前选中的Tab一致
		if (activeTab.value === 'today') {
			queryParams.value.type = 'progress' // 今日在招
		} else if (activeTab.value === 'pre') {
			queryParams.value.type = 'ready' // 预招岗位
		}
	}
}

// 设置定时器，定期检查时间状态
const setupTimeCheckTimer = () => {
	// 每分钟检查一次时间状态
	setInterval(() => {
		checkTimeAndUpdateTabs()
	}, 60000) // 60000毫秒 = 1分钟
}

onMounted(async () => {
	console.log('找工作页面加载完成')
	
	// 检查当前时间，如果超过下午3点，则隐藏今日在招选项
	checkTimeAndUpdateTabs()
	
	// 设置定时器，每分钟检查一次时间状态
	setupTimeCheckTimer()
	
	// 获取热门城市列表
	await getHotCities()
	try {
		// 先自动登录获取openId，再初始化数据
		await fetchJobList()
	} catch (error) {
		console.error('页面初始化失败:', error)
		// 如果初始化失败，显示错误提示
		uni.showToast({
			title: '页面加载失败，请重试',
			icon: 'none',
			duration: 2000
		})
	}
})

// 页面显示时自动刷新数据
onShow(async () => {
	console.log('找工作页面显示，自动刷新数据')
	
	// 检查当前时间并更新Tab显示状态
	checkTimeAndUpdateTabs()
	
	// 重置分页状态
	currentPage.value = 1
	finished.value = false
	
	// 刷新岗位列表数据
	try {
		await fetchJobList()
		console.log('页面显示时数据刷新完成')
	} catch (error) {
		console.error('页面显示时数据刷新失败:', error)
	}
})

// 自动登录获取openId
async function autoLogin() {
	try {
		// 检查是否已经有openId
		const existingOpenId = userStore.getOpenId()
		if (existingOpenId) {
			console.log('已有openId:', existingOpenId)
			return
		}
		
		console.log('开始自动登录获取openId')
		
		// 调用微信登录
		const loginResult = await uni.login()
		console.log('微信登录结果:', loginResult)
		
		if (loginResult.code) {
			console.log('微信登录成功，获取到code:', loginResult.code)
			
			// 将code发送到后端换取openId
			console.log('开始调用后端getOpenId接口...')
			const result = await userApi.getOpenId(loginResult.code)
			console.log('后端getOpenId接口返回:', result)
			
			if (result && result.code === 200) {
				const openId = result.data.openId
				console.log('获取到openId:', openId)
				
				if (openId) {
					// 将openId存储到用户缓存
					const success = userStore.setOpenId(openId)
					if (success) {
						console.log('openId存储成功')
						// 验证存储是否成功
						const storedOpenId = userStore.getOpenId()
						console.log('验证存储的openId:', storedOpenId)
					} else {
						console.error('openId存储失败')
					}
				} else {
					console.error('openId为空，接口返回数据:', result)
				}
			} else {
				console.error('获取openId失败:', result?.msg || result?.message || '接口返回错误')
				console.error('完整错误信息:', result)
			}
		} else {
			console.error('微信登录失败，loginResult:', loginResult)
		}
	} catch (error) {
		console.error('自动登录失败:', error)
		console.error('错误详情:', error.message)
	}
}
</script>

<style lang="scss" scoped>
/* 全面屏适配变量 */
:root {
	--status-bar-height: 44px;
	--safe-area-top: env(safe-area-inset-top);
	--safe-area-bottom: env(safe-area-inset-bottom);
}

.jobs-page {
	height: 100vh;
	background-color: #F5F5F5;
	overflow: hidden;
	display: flex;
	flex-direction: column;
}

.header-bg{
background: radial-gradient(118.27% 92.72% at 3.3333333333333335% 7.282913165266107%, var(--u-primary) 0%, var(--u-primary-light) 61.8%, var(--u-primary-plain) 90.28%, var(--u-primary-plain-disabled) 100%);
}

.time-status-indicator {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8rpx;
	padding: 12rpx 20rpx;
	background: linear-gradient(90deg, rgba(255, 107, 53, 0.1), rgba(255, 107, 53, 0.05));
	border-bottom: 1rpx solid rgba(255, 107, 53, 0.2);
	
	.status-text {
		font-size: 24rpx;
		color: var(--u-primary);
		font-weight: 500;
	}
}
/* 头部样式 */
.header {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background-color: transparent !important;
	
	
	
}

/* 状态栏占位 */
.status-bar {
	height: var(--status-bar-height);
	background-color: transparent;
}

/* 头部内容 */
.header-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	padding-top: calc(20rpx + env(safe-area-inset-top));
	padding-bottom: 20rpx;
}

.header-left {
	flex: 1;
	.logo {
		display: flex;
		align-items: center;
		.logo-text {
			font-size: 32rpx;
			font-weight: bold;
			color: var(--u-primary);
		}
		.logo-img{
			width: 50rpx;
			height: 50rpx;
			margin-right: 12rpx;
		}		
		.logo-sub {
			font-size: 20rpx;
			color: #999999;
			margin-left: 10rpx;
		}
	}
}

.header-center {
	flex: 1;
	text-align: center;
	.slogan {
		font-size: 28rpx;
		color: var(--u-primary);
		font-weight: 500;
	}
}

.header-right {
	display: flex;
	align-items: center;
	gap: 20rpx;
	flex: 1;
	justify-content: flex-end;
	
	.header-icon {
		width: 48rpx;
		height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background-color: rgba(248, 248, 248, 0.8);
	}
}

/* 搜索区域样式 */
.search-section {
	padding: 20rpx 30rpx;
	margin-bottom: 20rpx;
	margin-top: calc(var(--status-bar-height) + 80rpx + env(safe-area-inset-top));
}

.tab-container {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20rpx;
}

.tab-tabs {
	display: flex;
	gap: 40rpx;
}

.tab-item {
	position: relative;
	padding-bottom: 0rpx;
	
	.tab-text {
		font-size: 32rpx;
		color: #999999;
		font-weight: 500;
	}
	
	.tab-underline {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 100%;
		height: 6rpx;
		background: linear-gradient(270deg, var(--u-primary-plain-active), var(--u-primary));
		border-radius: 2rpx;
	}
	
	&.active {
		.tab-text {
			color: #333;
			font-weight: bold;
		}
	}
}

.search-icon {
	margin-left: 20rpx;
}

.time-notice {
	margin-left: 20rpx;
	padding: 8rpx 16rpx;
	background-color: rgba(255, 107, 53, 0.1);
	border-radius: 16rpx;
	border: 1rpx solid rgba(255, 107, 53, 0.3);
	
	.notice-text {
		font-size: 22rpx;
		color: var(--u-primary);
		font-weight: 500;
	}
}

.city-tabs {
	white-space: nowrap;
	margin-bottom: 20rpx;
	
	.city-tab {
		display: inline-block;
		margin-right: 20rpx;
		font-size: 28rpx;
	
		&.active {
			color: var(--u-primary);
			font-weight: bold;
		}
	}
}

.filter-tabs {
	white-space: nowrap;
	.filter-tab {
		display: inline-block;
		padding: 10rpx 20rpx;
		margin-right: 15rpx;
		font-size: 24rpx;
    color: #666666;
    background-color: #F5F5F5;
    border-radius: 15rpx;
    border: 1rpx solid transparent;
    transition: all .2s ease;
		
		&.active {
      color: var(--u-primary);
      // background-color: rgba(255, 107, 53, 0.12); /* 主題色的淺色底 */
      border-color: var(--u-primary);
      font-weight: 600;
		}
	}
}

/* 工作列表样式 */
.job-list {
	flex: 1;
	padding: 12rpx;
	padding-top: 8rpx;
	padding-bottom: env(safe-area-inset-bottom);
	margin-bottom: 100rpx;
	
	background-color: rgb(243, 243, 245);
	overflow-y: auto;
}

/* 空列表時，讓空狀態區域白底鋪滿可視高度 */
.job-list.is-empty {
  background-color: #FFFFFF;
}

.job-card {
	background-color: #FFFFFF;
	border-radius: 16rpx;
	padding: 30rpx;
	box-sizing: border-box;
	width: 100%;
	overflow: hidden;
	width: 94%;
	margin: 0 auto;
	margin-bottom: 20rpx;
}

.job-header {
	display: flex;
	justify-content: space-between;
	align-items: start;
	margin-bottom: 20rpx;
	
	.job-date {
		width: 70%;
		.date-text {
			font-size: 28rpx;
			color: var(--u-primary);
			font-weight: bold;
			
		}
		.job-title-box{
			display: inline-flex;
			align-items: center;
			background-color: var(--u-primary-light);
			border-radius: 10rpx;
			font-size: 18rpx;
			width: 180rpx;
		}
		.job-title-text{
			vertical-align: 2px;
			margin-left: 10rpx;
		}
	}
	
	.job-salary {
		font-size: 32rpx;
		font-weight: bold;
		color: var(--u-red);
	}
}

.job-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 15rpx;
	line-height: 1.4;
	
}

.job-location {
	font-size: 26rpx;
	color: #999999;
	margin-bottom: 20rpx;
}

.job-tags {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx;
	margin-bottom: 20rpx;
	
	.job-tag {
		display: flex;
		align-items: center;
		padding: 8rpx 16rpx;
		background-color: #F5F5F5;
    border-radius: 10rpx; /* 圓角縮小 */
		
		.tag-icon {
      display: none; /* 移除圖標顯示 */
		}
		
		.tag-text {
			font-size: 22rpx;
			color: #666666;
		}
	}
}

.job-positions {
	display: flex;
	align-items: flex-start;
	margin-bottom: 20rpx;
	
	.positions-label {
		font-size: 24rpx;
		color: #666666;
		margin-right: 8rpx;
		flex-shrink: 0;
	}
	
	.positions-text {
		font-size: 24rpx;
		color: #333333;
		line-height: 1.4;
		flex: 1;
	}
}

.job-engagement {
	display: flex;
	align-items: center;
	justify-content: space-between;
  border-top: 1rpx solid #F2F3F5; /* 更細更淡的分割線 */
  padding-top: 12rpx;
	
	.engagement-left {
		display: flex;
		align-items: center;
		
		.user-avatars {
			display: flex;
			margin-right: 15rpx;
			
			.user-avatar {
				width: 40rpx;
				height: 40rpx;
				border-radius: 50%;
				background-color: #F0F0F0;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 20rpx;
				margin-right: -10rpx;
				border: 2rpx solid #FFFFFF;
			}
		}
		
		.engagement-text {
			font-size: 24rpx;
			color: var(--u-primary);
		}
	}
	
	.apply-btn {
		background-color: var(--u-primary);
		border-radius: 20rpx;
		padding: 12rpx 24rpx;
		cursor: pointer;
		transition: all 0.3s ease;
		
		&.disabled {
			background-color: #CCCCCC;
			cursor: not-allowed;
			opacity: 0.6;
		}
		
		.apply-text {
			font-size: 24rpx;
			color: #FFFFFF;
			font-weight: 500;
		}
	}
}
	
.filter-box{
	display: flex;
	justify-content: space-between;
	align-items: center;
	.filter-right{
		display: flex;
		justify-content: flex-end;
		width: 360rpx;
		.filter-select{
			margin-left: 12rpx;
			display: flex;
			align-items: center;
			gap: 8rpx;
			padding: 4rpx 6rpx;
			border-radius: 8rpx;
			background-color: #F8F8F8;
			
			.filter-text {
				font-size: 24rpx;
				color: #666666;
			}
		}
	}
}

/* 日历弹窗样式 */
.calendar-popup {
	background-color: #FFFFFF;
	border-radius: 20rpx 20rpx 0 0;
	padding: 40rpx 30rpx;
	min-height: 600rpx;
}

.calendar-header {
	text-align: center;
	margin-bottom: 40rpx;
	
	.calendar-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
	}
}

.calendar-content {
	.calendar-grid {
		display: grid;
		grid-template-columns: repeat(7, 1fr);
		gap: 8rpx;
		margin-top: 20rpx;
	}
	
	.calendar-day {
		aspect-ratio: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 8rpx;
		position: relative;
		
		.day-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 100%;
		}
		
		.day-text {
			font-size: 28rpx;
			color: #333333;
			font-weight: 500;
		}
		
		.job-count {
			font-size: 20rpx;
			color: var(--u-primary);
			margin-top: 4rpx;
			font-weight: bold;
		}
		
		.no-job-text {
			font-size: 20rpx;
			color: #CCCCCC;
			margin-top: 4rpx;
		}
		
		&.other-month {
			.day-text {
				color: #CCCCCC;
			}
		}
		
		&.has-jobs {
			background-color: #FFF5F0;
			border: 2rpx solid var(--u-primary);
			
			&.selected {
				background-color: var(--u-primary);
				
				.day-text, .job-count {
					color: #FFFFFF;
				}
			}
		}
		
		&.no-jobs {
			.day-text {
				color: #CCCCCC;
			}
		}
		
		&.today {
			&.has-jobs {
				background-color: #FFF5F0;
				border: 2rpx solid var(--u-primary);
				
				.day-text {
					color: var(--u-primary);
					font-weight: bold;
				}
			}
		}
		
		&.disabled {
			.day-text {
				color: #CCCCCC;
			}
		}
	}
}

.month-nav {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 30rpx;
	
	.nav-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background-color: #F5F5F5;
	}
	
	.month-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
	}
}

.weekdays {
	display: grid;
	grid-template-columns: repeat(7, 1fr);
	gap: 8rpx;
	margin-bottom: 20rpx;
	
	.weekday {
		aspect-ratio: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #999999;
		font-weight: 500;
	}
}

.calendar-tip {
	margin-top: 30rpx;
	padding-top: 20rpx;
	text-align: center;
	
	.tip-text {
		font-size: 24rpx;
		color: #FF4444;
		line-height: 1.4;
	}
}
/* 实名认证卡片样式 */
.verification-card {
	margin-bottom: 10rpx;
	background: linear-gradient(135deg, #e8f0f8 0%, #d5e7fb 100%);
	border-radius: 16rpx;
	padding: 20rpx 30rpx;
	border: 2rpx solid #fff;
	margin-left: 20rpx;
	margin-right: 20rpx;
}

.verification-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.verification-left {
	display: flex;
	align-items: center;
	flex: 1;
	
	.avatar-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		margin-right: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		.avatar-icon-img{
			width: 80rpx;
			height: 80rpx;
		}
	}
	
	.verification-text {
		flex: 1;
		.main-text {
			display: block;
			font-size: 28rpx;
			font-weight: bold;
			color: #333333;
			margin-bottom: 10rpx;
			line-height: 1.4;
		}
		
		.sub-text {
			display: block;
			font-size: 22rpx;
			color: #666666;
			line-height: 1.3;
		}
	}
}

.verification-right {
	flex-shrink: 0;
}

/* 空数据占位符样式 */
.empty-state {
	
	border-radius: 16rpx;
	padding: 60rpx 30rpx;
	margin-bottom: 30rpx;
  text-align: center;
  min-height: calc(100vh - 240rpx - var(--status-bar-height) - env(safe-area-inset-top) - env(safe-area-inset-bottom));
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding-top: 60rpx; /* 往上放一些空間 */
	
	.empty-illustration {
		width: 400rpx;
		height: 300rpx;
		margin: 0 auto;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: -100rpx;
	}
	
	.empty-text {
		display: block;
		font-size: 28rpx;
		color: #999;
		margin-bottom: 40rpx;
	}
	
	.empty-actions {
		display: flex;
		gap: 20rpx;
		justify-content: center;
		
		.action-btn {
			flex: 1;
			max-width: 300rpx;
			padding: 20rpx 30rpx;
			border-radius: 12rpx;
			text-align: center;
			
			&.refresh-btn {
				background-color: var(--u-primary);
				
				.btn-text {
					font-size: 26rpx;
					color: #FFFFFF;
				}
			}
		}
	}
}

/* 页面加载指示器样式 */
.loading-indicator {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 30rpx;
	text-align: center;
	
	.loading-text {
		margin-top: 30rpx;
		font-size: 28rpx;
		color: #666666;
	}
}

/* Loading状态样式 */
.loading-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 40rpx 0;
	background-color: #FFFFFF;
	border-radius: 16rpx;
	margin: 0 12rpx 15rpx;
	
	.loading-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #999999;
	}
}
</style> 